package com.zhidisoft.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhidisoft.common.Page;
import com.zhidisoft.system.dao.IRoleDao;
import com.zhidisoft.system.dao.IUserDao;
import com.zhidisoft.system.entity.Role;
import com.zhidisoft.system.entity.User;
import com.zhidisoft.system.service.IUserService;
import com.zhidisoft.system.vo.UserVO;

@Service
public class UserServiceImpl implements IUserService {
	
	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IRoleDao roleDao;

	@Override
	public String add(User user) {
		return userDao.save(user);
	}

	
	@Override
	public boolean updateRoles(String userId, String... roleId) {
		if(userId != null && roleId!=null && roleId.length>0){
			User user = userDao.get(userId);
			
			//解除user与原有角色的关系
			user.getRoles().clear();
			//根据roleId获取到对应的角色，把角色和当前的用户关联起来
			for(String rid : roleId){
				Role role = new Role();
				role.setId(rid);
				user.getRoles().add(role);
			}
			return true;
		}
		return false;
	}

	
	@Override
	public boolean addRoles(String userId, String... roleId) {
		if(userId != null && roleId!=null && roleId.length>0){
			//获取用户信息
			User user = userDao.get(userId);
			for(String rid : roleId){
				//获取角色信息
				Role role = new Role();
				role.setId(rid);
				//将角色信息添加给用户
				user.getRoles().add(role);
			}
			return true;
		}
		return false;
	}


	@Override
	public User findByUsername(String username) {
		if(!StringUtils.isBlank(username)){
			return userDao.findByUsername(username);
		}
		return null;
	}


	@Override
	public Page<UserVO> findByPage(Long pageNumber, Long pageSize) {
		//获取到数据库中用户总数量
		Long totalRows = userDao.count();
		//创建Page对象
		Page<UserVO> page = new Page<UserVO>();
		page.setPageNumber(pageNumber);
		page.setPageSize(pageSize);
		page.setTotalRows(totalRows);
		//获取对应的数据记录
		List<User> list = userDao.findByPage(page.getPageNumber(),page.getPageSize());
		List<UserVO> result = new ArrayList<UserVO>();
		for(User user : list){
			result.add(UserVO.fromUser(user));
		}
		page.setResult(result);
		return page;
	}


	@Override
	public boolean saveOrUpdate(User user) {
		userDao.saveOrUpdate(user);
		return true;
	}


	@Override
	public boolean removeByIds(String ids) {
		String[] userIds = ids.split(",");
		return userDao.delete(userIds);
	}


	@Override
	public UserVO findById(String id) {
		
		return UserVO.fromUser(userDao.get(id));
	}

	

}
